import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Button, message, Modal } from 'antd';
import React, { Component } from 'react';
// import { modifyPassword } from "../../services/security";
// import { logout } from "../../services/user";
import styles from './style.less';
import Router from "umi/router";
import {modifyPassword} from "@/services/login";
import {loginOut} from "@/services/user";
const FormItem = Form.Item;

function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

const forge = require('node-forge');
const UpdatePassword = Form.create({ name: 'UpdatePassword' })(
  class extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        passwordUpdateVisible: false,
      }
    }

    state = {
      confirmDirty: false,
    };


    handleSubmit() {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          if (values.newPassword === values.reNewPassword) {
            let md = forge.md.md5.create();
            let md2 = forge.md.md5.create();
            md.update(values.newPassword);
            md2.update(values.oldPassword);
            let newEncryptionPassword = md.digest().toHex();
            let oldEncryptionPassword = md2.digest().toHex();
            modifyPassword(oldEncryptionPassword, newEncryptionPassword).then(res => {
              if (res.retCode === "0") {
                message.success('密码修改成功')
                loginOut().then(res => {
                  sessionStorage.clear();
                  Router.push(`/?tenantUrl=` + 'default');
                });
              } else {
                message.error('密码修改失败')
              }
            })
          } else {
            message.error("新密码两次输入不一致")
          }
        }
      });
    }

    validateToNextPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && this.state.confirmDirty) {
        form.validateFields(['confirm'], { force: true });
      }
      // if (!(value && value.length >= 8)) {
      //   callback("密码长度应不小于8位")
      // }
      callback();
    };
    handleConfirmBlur = (e) => {
      const value = e.target.value;
      this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    }
    compareToFirstPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && value !== form.getFieldValue('newPassword')) {
        callback('两次密码输入不一致');
      } else {
        if (value && !/^\w{4,16}$/.test(value)) {
          callback('密码允许字母、数字和下划线，长度4-16位!');
        } else {
          callback();
        }
      }
    }

    handleCancel() {
      if (this.props.handleCancel) {
        this.props.handleCancel();
      }
    }
    validateToNextPassword = (rule, value, callback) => {
      const { getFieldValue } = this.props.form;
      const { form } = this.props;
      const reg = /^\w{4,16}$/
      if (value && !reg.test(value)){
        callback('密码格式错误！密码长度4-16位')
      }
      if (value && this.state.confirmDirty) {
        form.validateFields(['reNewPassword'], { force: true });
      }
      callback()
      // //是否包含数字
      // var ptr_digit = /^.*[0-9]+.*$/;
      // //是否包含字母
      // var ptr_lowcase = /^.*[a-zA-Z]+.*$/;
      // //是否包含特殊字符（非数字、字母的字符）
      // var ptr_special = /((?=[\x21-\x7e]+)[^A-Za-z0-9])/;
      //
      // if (value && getFieldValue('confirmPassword') && value !== getFieldValue('confirmPassword')) {
      //   callback('两次密码输入不一致');
      // } else if (value.length < 8) {
      //   callback(new Error('密码至少8位'));
      // } else if (
      //   (ptr_digit.test(value) && ptr_lowcase.test(value) && ptr_special.test(value)) ||
      //   (ptr_digit.test(value) && ptr_lowcase.test(value) && !ptr_special.test(value))
      // ) {
      //   callback();
      // } else {
      //   callback(new Error('至少包含字母、数字字符中的两类字符'));
      // }
    };
    render() {
      const { getFieldDecorator } = this.props.form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 },
        },
      };
      // Only show error after a field is touched.
      return <Modal visible={this.props.passwordUpdateVisible} title={"修改密码"} maskClosable={false} width={500}
                    onCancel={this.handleCancel.bind(this)}
                    okText={"确认"}
                    cancelText={"取消"}
                    onOk={this.handleSubmit.bind(this)}/*disabled={hasErrors(getFieldsError())}*/
      >
        <div className={styles.kg_user_container}>
          <Form>
            <FormItem label="原密码" {...formItemLayout}>
              {getFieldDecorator('oldPassword', {
                rules: [
                  {
                    required: true, message: '请输入正确的密码!'
                  },
                ],
              })(
                <Input type="password" placeholder="请输入原密码" />
              )}
            </FormItem>
            <FormItem label="新密码" {...formItemLayout} >
              {getFieldDecorator('newPassword', {
                rules: [{
                  required: true, message: '请输入新密码'},{
                  validator: this.validateToNextPassword,
                }]
              })(
                <Input type="password" placeholder="请输入新密码" />
              )}
            </FormItem>
            <FormItem label="确认密码" {...formItemLayout} >
              {getFieldDecorator('reNewPassword', {
                rules: [{
                  required: true, message: '请再次输入新密码'
                }, {
                  validator: this.compareToFirstPassword,
                }],
              })(
                <Input type="password" onBlur={this.handleConfirmBlur} placeholder="请确认新密码" />
              )}
            </FormItem>
            {/*  <FormItem>
          <Button style={{width: "100%"}} type="primary" htmlType="submit" disabled={hasErrors(getFieldsError())}>
            <span style={{color:"black"}}>确 认</span>
          </Button>
        </FormItem>*/}
          </Form>
        </div>
      </Modal>

    }
  }
)
export default UpdatePassword
